package com.vt.auth.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.vt.admin.api.entity.SysLoginLog;
import com.vt.admin.api.feign.RemoteLogService;
import com.vt.common.security.handler.AuthenticationSuccessEventHandler;
import com.vt.common.security.service.CustomUser;
import com.vt.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: PanZha
 * @Date: 2018/10/12 16:30
 */
@Slf4j
@Component
@AllArgsConstructor
public class DefaultAuthenticationSuccessEventHandler extends AuthenticationSuccessEventHandler {

    private final RemoteLogService remoteLogService;

    /**
     * 处理登录成功方法
     *
     * @param authentication 登录对象
     */
    @Override
    public void handle(Authentication authentication) {
        log.info("用户：{} 登录成功", authentication.getPrincipal());

        CustomUser user = SecurityUtils.getUser(authentication);
        //记录登录日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        SysLoginLog logVo = new SysLoginLog()
                .setLoginAccount(user.getUsername())
                .setLoginIp(HttpUtil.getClientIP(request))
                .setLoginTime(DateUtil.date())
                .setLoginUser(user.getId())
                .setServiceId(SecurityUtils.getClientId())
                .setLoginType(1);

        remoteLogService.saveLoginLog(logVo);
    }
}
